package factorytest.iflytek.com.einkiflytekfactorytest.agingtest;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;

import factorytest.iflytek.com.einkiflytekfactorytest.R;
import factorytest.iflytek.com.einkiflytekfactorytest.common.SettingsUtils;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.DebugLog;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.SystemPropertyUtil;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.TimeStringUtils;

public class TestSleep extends AgingTestItemBase {

    private final static String SLEEP_ACTION = "com.rockchip.sleep.ACTION_TEST_CASE_SLEEP";

    private final long AWAKE_TIME = 5000L;

    private long SLEEP_TIME = 20000L;
    private int SCREEN_OFF_TIME = 15000;

    private static final int MSG_UPDATE_UI = 100;
    private static final int PERIOD_UPDATE_UI = 5000;


    public TestSleep(Context context, View view) {
        super(context, view);

        String sleepTimeString = SystemPropertyUtil.getSystemProperty("persist.aging.sleep_time");
        if (!TextUtils.isEmpty(sleepTimeString) && TextUtils.isDigitsOnly(sleepTimeString)) {
            SLEEP_TIME = Long.parseLong(sleepTimeString);
        }

        String screenOffTimeString = SystemPropertyUtil.getSystemProperty("persist.aging.screen_off_time");
        if (!TextUtils.isEmpty(screenOffTimeString) && TextUtils.isDigitsOnly(screenOffTimeString)) {
            SCREEN_OFF_TIME = Integer.parseInt(screenOffTimeString);
        }

    }

    @Override
    public void handleMessage(Message msg) {
        final int what = msg.what;
        switch (what) {
            case MSG_UPDATE_UI:
                updateUI();
                getHandler().sendEmptyMessageDelayed(MSG_UPDATE_UI, PERIOD_UPDATE_UI);
                break;
        }
    }

    @Override
    protected void doStartTest() {

        DebugLog.e("TestSleep doStartTest");

        IntentFilter filter = new IntentFilter(SLEEP_ACTION);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        getContext().registerReceiver(sleepTestReceiver, filter);

        startTestSleep();
        getHandler().sendEmptyMessage(MSG_UPDATE_UI);
    }

    @Override
    protected void doStopTest() {

        DebugLog.e("TestSleep doStopTest");

        turnOnScreen();
        stopAlarm();
        getContext().unregisterReceiver(sleepTestReceiver);
        getHandler().removeMessages(MSG_UPDATE_UI);

        SettingsUtils.setScreenOffTimeForFT(getContext());
    }

    @Override
    public AgingTestItemAttr getAgingTestItemAttr() {
        return AgingTestItemAttr.sleep;
    }

    private void startTestSleep() {

        stopAlarm();

        try {
            SettingsUtils.setScreenOffTime(getContext(), SCREEN_OFF_TIME);
            setAlarm(SLEEP_TIME, true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setAlarm(long intervalMillis, boolean repeat) {
        AlarmManager alarmManager = (AlarmManager) getContext()
                .getSystemService(Context.ALARM_SERVICE);

        if (alarmManager == null) {
            return;
        }

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getContext(), 0, new Intent(SLEEP_ACTION), 0);

        if (repeat) {
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    intervalMillis + System.currentTimeMillis(), intervalMillis,
                    pendingIntent);
        }
    }

    private void stopAlarm() {

        PendingIntent localPendingIntent = PendingIntent.getBroadcast(
                getContext(), 0, new Intent(SLEEP_ACTION), 0);
        AlarmManager alarmManager = ((AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE));

        if (alarmManager != null) {
            alarmManager.cancel(localPendingIntent);
        }
    }

    private void updateUI() {

        final long usedTime = AgingTestItemAttr.getAgingTimeTick_ms(getContext()) - getAgingTestItemAttr().getStartTime_ms(getContext());
        final String timeStr = TimeStringUtils.makeTimeString(usedTime);

        String info = getContext().getString(R.string.aging_sleep_info,
                SCREEN_OFF_TIME / 1000,
                SLEEP_TIME / 1000, getAgingTestItemAttr().getTestCount(getContext()),
                timeStr);
        updateTxtItemInfo(info);

    }


    private BroadcastReceiver sleepTestReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context mContext, Intent intent) {
            final String action = intent.getAction();
            if (action == null) {
                return;
            }
            DebugLog.e("SleepTestReceiver onReceive, action = " + action);

            if (action.equals(SLEEP_ACTION)) {
                int count = getAgingTestItemAttr().getTestCount(getContext());
                count += 1;
                getAgingTestItemAttr().setTestCount(mContext, count);

                updateUI();

                turnOnScreen();

            } else if (action.equals(Intent.ACTION_SCREEN_ON)) {

                getHandler().sendEmptyMessage(MSG_UPDATE_UI);

            } else{ if (action.equals(Intent.ACTION_SCREEN_OFF)) {

                getHandler().removeMessages(MSG_UPDATE_UI);

            }}

        }

    };

    private void turnOnScreen() {
        PowerManager pw = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
        if (pw != null) {
            pw.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK,
                    "factoryTest:ScreenOnTimer").acquire(AWAKE_TIME);
        }

        KeyguardManager km = (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
        if (km != null) {
            km.newKeyguardLock("TestCaseSleep").disableKeyguard();
        }
    }

}
